namespace Filters.Demo.Core.FilterConfiguration
{
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;

    /// <summary>
    /// FilterElement class
    /// </summary>
    [XmlRoot("filter")]
    public class FilterElement
    {
        public FilterElement()
        {
            this.FilterParameters = new FilterParametersElement();    
        }

        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("type")]
        public string Type { get; set; }

        [XmlElement("filterParameters")]
        public FilterParametersElement FilterParameters { get; set; }

        public override string ToString()
        {
            if (this.FilterParameters.FilterParameters.Count == 0)
            {
                return this.Name;
            }

            var builder = new StringBuilder();

            builder
                .Append(this.Name)
                .Append(" { ");

            foreach (var parameter in this.FilterParameters.FilterParameters)
            {
                builder
                    .Append(parameter.Name)
                    .Append(" = ");

                if (!string.IsNullOrEmpty(parameter.Value))
                {
                    builder.Append(parameter.Value);
                }
                else
                {
                    builder.Append(" { ");
                    foreach (var parameterValue in parameter.FilterParameterValues)
                    {
                        builder
                            .Append(parameterValue.Value)
                            .Append((parameter.FilterParameterValues.Last() == parameterValue) ? " " : ", ");
                    }

                    builder.Append("} ");
                }

                builder.Append((this.FilterParameters.FilterParameters.Last() == parameter) ? " " : ", ");
            }

            builder.Append("}");

            return builder.ToString();
        }
    }
}